﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Collections.Specialized;
using System.Text;

namespace BEELab.Data
{
    public class HTTPHelper
    {
        /// <summary>
        /// Gets URL and Data, uploads the data to the resource specified in the URL,
        /// and returns client's response
        /// </summary>
        /// <param name="url">url string</param>
        /// <param name="data">Key-Value pairs as a string, seperated by '&'.
        /// Format: 'Key=Value&Key=Value'</param>
        /// <returns>Decoded bytes of client's response as a string</returns>
        public static string Post(string url, string data)
        {
            try
            {
                var client = new WebClient();
                var values = new NameValueCollection();

                //Split date into an array
                string[] kvSplit;
                foreach (string kvPair in data.Split('&'))
                {
                    kvSplit = kvPair.Split('=');
                    values[kvSplit[0]] = kvSplit[1];
                }

                //Upload data values to client
                var response = client.UploadValues(url, values);

                return Encoding.Default.GetString(response);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// Gets client URL and returns client's data
        /// </summary>
        /// <param name="url">client URL string</param>
        /// <returns>Client data</returns>
        public static string Get(string url)
        {
            try
            {
                var client = new WebClient();
                return client.DownloadString(url);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}